package com.hrt.common.web;

import com.btcode.common.AbstractSingleton;
import com.btcode.db.sqlparameter.PageInfo;
import com.btcode.exception.MsgException;
import com.btcode.orm.filter.IFilter;
import com.btcode.orm.model.IModel;
import com.btcode.orm.model.ModelPageResult;
import com.btcode.web.core.annotation.RequestMapping;
import com.btcode.web.core.controller.Controller;
import com.btcode.web.core.respone.ResultFlag;
import com.btcode.web.core.unit.WebContext;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class BaseController extends Controller {

    protected IService service;
    private IModel tempModel;

    protected <T extends IModel> void initModelClass(T modelClass) {
        this.tempModel = modelClass;
    }

    protected <T extends BaseService> void initServiceClass(Class<T> serviceClass) {
        service = AbstractSingleton.getInstance(serviceClass);
    }

    @RequestMapping(path = "get-model")
    public void getModel(ServletRequest arg0, ServletResponse arg1) throws IOException {
        IModel model = getService().getModel(getRequestModel());
        success(model);
    }

    @RequestMapping(path = "list-model")
    public void listModel(ServletRequest arg0, ServletResponse arg1) throws IOException {
        List<IFilter> filters = RequestUnit.getModelFilter(tempModel.getClass());
        String orderString = RequestUnit.getString("orderString");
        PageInfo pageInfo = RequestUnit.getPageInfo();
        ModelPageResult models = getService().listModel(tempModel.getClass(), filters, orderString, pageInfo);
        success(models);
    }

    @RequestMapping(path = "create")
    public void create(ServletRequest arg0, ServletResponse arg1) throws IOException {
        getService().create(getRequestModel());
        success("创建成功");
    }

    @RequestMapping(path = "creates")
    public void creates(ServletRequest arg0, ServletResponse arg1) throws IOException {
        getService().creates(getRequestModels());
        success("创建成功");
    }

    @RequestMapping(path = "update")
    public void update(ServletRequest arg0, ServletResponse arg1) throws IOException {
        getService().update(getRequestModel());
        success("修改成功");
    }

    @RequestMapping(path = "delete")
    public void delete(ServletRequest arg0, ServletResponse arg1) throws IOException {
        getService().delete(getRequestModel());
        success("删除成功");
    }

    protected IService getService() {
        if (service == null) {
            throw new MsgException("请调用BaseController的initServiceClass方法进行初始化");
        }
        return service;
    }

    protected <T extends AbstractSingleton> T getService(Class<T> serviceClass) {

        T s = AbstractSingleton.getInstance(serviceClass);

        return s;
    }

    private IModel getRequestModel() {
        if (tempModel == null) {
            throw new MsgException("请调用BaseController的initModelClass方法进行初始化");
        }
        String parameterType = WebContext.getRequest().getHeader("Parameter-Type");
        if (parameterType != null && parameterType.contains("un-flatten")) {//非扁平化
            return JsonRequestUnit.getModel(tempModel.getClass(),
                    JsonRequestUnit.getString("data"));
        } else {
            return RequestUnit.getModel(tempModel.getClass());
        }
    }

    private List<? extends IModel> getRequestModels() {
        if (tempModel == null) {
            throw new MsgException("请调用BaseController的initModelClass方法进行初始化");
        }
        String parameterType = WebContext.getRequest().getHeader("Parameter-Type");
        if (parameterType != null && parameterType.contains("un-flatten")) {//非扁平化
            return JsonRequestUnit.getModels(tempModel.getClass(),
                    JsonRequestUnit.getString("data"));
        } else {
            return RequestUnit.getModels(tempModel.getClass());
        }
    }

    public static String toUtf8String(HttpServletRequest request, String string) {
        String agent = request.getHeader("User-Agent");
        try {
            boolean isFireFox = (agent != null && agent.toLowerCase().indexOf("firefox") != -1);
            if (isFireFox) {
                string = new String(string.getBytes("UTF-8"), "ISO8859-1");
            } else {
                string = toUtf8String(string);
                if ((agent != null && agent.indexOf("MSIE") != -1)) {
                    if (string.length() > 150) {
                        // 根据request的locale 得出可能的编码
                        string = new String(string.getBytes("UTF-8"), "ISO8859-1");
                    }
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return string;
    }

    public static String toUtf8String(String string) {

        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < string.length(); i++) {
            char c = string.charAt(i);
            if (c >= 0 && c <= 255) {
                sb.append(c);
            } else {
                byte[] b;
                try {
                    b = Character.toString(c).getBytes("utf-8");
                } catch (Exception ex) {
                    b = new byte[0];
                }
                for (int j = 0; j < b.length; j++) {
                    int k = b[j];
                    if (k < 0) {
                        k += 256;
                    }
                    sb.append("%" + Integer.toHexString(k).toUpperCase());
                }
            }
        }
        return sb.toString();
    }

    @Override
    public void success(Object obj) throws IOException {
        AbstractSingleton.getInstance(JsonRespone.class).outputObj(obj, ResultFlag.SUCCESS,
                "WELL DONE");
    }
}
